#!/usr/bin/env python3
# filename: main.py

from os import path
from uuid import uuid4
import pdb
import random

from flask import (
        abort,
        flash,
        url_for,
        redirect,
        render_template,
        Blueprint,
        request,
        session,
        jsonify)

from flask_login import (
        login_user,
        logout_user,
        current_user)

from flask_principal import (
        current_app,
        Identity,
        AnonymousIdentity,
        identity_changed)
from hzsaiblog.forms import LoginForm, RegisterForm
from hzsaiblog.captcha import gen_captcha, gen_image
from hzsaiblog.models import db, User, Role
from hzsaiblog.extensions import github, login_manager

main_blueprint = Blueprint(
        'main',
        __name__,
        template_folder=path.join(path.pardir, 'templates', 'main'))


@main_blueprint.route('/')
def index():
    return redirect(url_for('blog.home'))


@main_blueprint.route('/login', methods=['GET', 'POST'])
def login():
    """Route for login."""

    form = LoginForm()

    # `post`
    if form.validate_on_submit():
        # Using session to check the user's login status
        # Add the user's name to cookie
        # session['username'] = form.username.data

        user = User.query.filter_by(username=form.username.data).one()
        login_user(user, remember=form.remember.data)

        flash('You have login successfully.', 'success')

        # the redirect url maybe unsave.
        # nexT = request.args.get('next')
        # if not is_safe_url(nexT):
        #     return abort(400)

        identity_changed.send(
                current_app._get_current_object(),
                identity=Identity(user.id))

        return redirect(url_for('blog.home'))

    # `get`
    return render_template('login.html', form=form)


@main_blueprint.route('/logout', methods=['GET', 'POST'])
def logout():
    """Route for logout."""

    # Remove the username from the cookie.
    # session.pop('username', None)

    # Using the flask_login to processing and check the logout status for user
    flash('You have logout successfully.', 'success')

    logout_user()

    identity_changed.send(
            current_app._get_current_object(),
            identity=AnonymousIdentity())

    return redirect(url_for('blog.home'))


@main_blueprint.route('/register', methods=['GET', 'POST'])
def register():
    """Route for register."""

    form = RegisterForm()
    randNum = 0
    captcha_str = ''
    image = None

    # `post`
    if form.validate_on_submit():
        user = User(
                id=str(uuid4()),
                username=form.username.data,
                password=form.password.data
                )
        role_poster = Role.query.filter_by(name='poster').first()
        role_poster.users.append(user)

        db.session.add(user)
        db.session.add(role_poster)
        db.session.commit()

        login_user(user)

        flash('You have register successfully.', 'success')
        return redirect(url_for('blog.home'))
    # pdb.set_trace()
    randNum = random.randint(0, 65535)
    captcha_str = gen_captcha()
    image = gen_image(captcha_str)
    image.save('hzsaiblog/static/images/captcha.png')
    session['captcha_key'] = captcha_str.lower()
    # print("Captcha: ", captcha_str.lower())
    return render_template('register.html', form=form, randNum=str(randNum))


@main_blueprint.route('/github')
def github_login():
    return github.authorize(
            callback=url_for(
                'main.github_authorized',
                _external=True))


@main_blueprint.route('/github/authorized', methods=['GET', 'POST'])
def github_authorized():

    resp = github.authorized_response()

    if resp is None or resp.get('access_token') is None:
        return 'Access denied: reason=%s error=%s resp=%s' % (
                request.args['error'],
                request.args['error_description'],
                resp)

    session['github_token'] = (resp['access_token'], '')
    me = github.get('user')

    # print("data--->: %s" % jsonify(me.data))
    # return jsonify(me.data)

    if me.data.get('first_name', False):
        github_username = me.data['first_name'] + " " + me.data['lase_name']
    else:
        github_username = me.data['name']

    user = User.query.filter_by(username=github_username).first()
    if user is None:
        user = User(id=str(uuid4()), username=github_username, password='12345678')
        db.session.add(user)
        db.session.commit()
        login_user(user)
        flash('You have logged in via github account, origin password:12345678')
        # return redirect(url_for('blog.editPersionInfo'))
        return redirect(url_for('blog.home'))

    login_user(user, force=True)
    flash('You have been logged in.', category='success')

    return redirect(url_for('blog.home'))
